<template>
    <div class="container_box">
        <el-scrollbar class="main_box">
            <div class="title-box">
                <span class="title">商户号设置</span>
                <!-- <span class="guide-text">配置引导</span> -->
            </div>

            <el-form
                ref="formInfo"
                :model="state.infoData"
                :rules="formRules"
                label-position="right"
                label-width="120px">
                <el-form-item label="IP地址：">
                    <div class="ip-box">
                        <span>{{ state.infoData.ip }}</span>
                        <el-button size="small" @click="onCopy(state.infoData.ip)">复制</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="商户号：" prop="merchant_sn">
                    <div class="cont-box">
                        <el-input v-model.trim="state.infoData.merchant_sn" placeholder="请输入商户号"></el-input>
                        <span class="guide-text" @click="goBlank(1)">如何查看商户号？</span>
                    </div>
                </el-form-item>
                <el-form-item label="支付秘钥：" prop="pay_secret">
                    <div class="cont-box">
                        <el-input v-model.trim="state.infoData.pay_secret" placeholder="请输入支付秘钥"></el-input>
                        <span class="guide-text" @click="goBlank(2)">如何查看支付秘钥？</span>
                    </div>
                </el-form-item>
                <el-form-item label="企业ID：" prop="wx_corp_id">
                    <div class="cont-box">
                        <el-input v-model.trim="state.infoData.wx_corp_id" placeholder="请输入企业ID"></el-input>
                        <span class="guide-text" @click="goBlank(3)">如何获取企业ID？</span>
                    </div>
                </el-form-item>
                <el-form-item label="证书序列号" prop="merchant_certificate_serial">
                    <div class="cont-box">
                        <el-input
                            v-model.trim="state.infoData.merchant_certificate_serial"
                            placeholder="请输入证书序列号"></el-input>
                        <span class="guide-text" @click="goBlank(4)">如何获取序列号？</span>
                    </div>
                </el-form-item>
                <el-form-item label="支付证书：" prop="apiclient">
                    <div class="cont-box">
                        <el-upload
                            ref="upload"
                            action="#"
                            :auto-upload="false"
                            :limit="2"
                            accept=".pem"
                            drag
                            class="upload-box"
                            :file-list="fileList"
                            :on-change="onHandleChange"
                            :on-remove="onRemoveUpload">
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">
                                <em v-if="state.infoData.apiclient_cert && state.infoData.apiclient_key"
                                    >已上传，可重新上传替换文件</em
                                >
                                <span v-else>点击或拖动上传文件</span>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">* 第一步先上传apiclient_cert.pem文件</div>
                                <div class="el-upload__tip">* 第二步再上传apiclient_key.pem文件</div>
                            </template>
                        </el-upload>
                        <a class="guide-text" @click="goBlank(5)">如何下载支付证书？</a>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit(formInfo)">保存</el-button>
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElForm, ElMessage } from 'element-plus';
import type { FormInstance, UploadProps, UploadUserFile, UploadRawFile } from 'element-plus';
import { getBusinesspay, setBusinesspay, setSavePem } from '@/api/channelconfig/enterprisepayment';
import useClipboard from 'vue-clipboard3';
import router from '@/router';

const { toClipboard } = useClipboard();

const validatePass = (rule: any, value: any, callback: any) => {
    if (state.infoData.apiclient_cert && state.infoData.apiclient_key) {
        if (fileList.value.length == 1) {
            callback(new Error('请选择相关文件'));
        } else {
            callback();
        }
    } else {
        if (fileList.value.length != 2) {
            callback(new Error('请选择相关文件'));
        } else {
            callback();
        }
    }
};

const formInfo = ref<FormInstance>();
const upload = ref();
const fileList = ref<UploadUserFile[]>([]);

const formRules = reactive({
    merchant_sn: [{ required: true, message: '请输入商户号', trigger: 'blur' }],
    pay_secret: [{ required: true, message: '请输入支付秘钥', trigger: 'blur' }],
    wx_corp_id: [{ required: true, message: '请输入企业ID', trigger: 'blur' }],
    merchant_certificate_serial: [{ required: true, message: '请输入证书序列号', trigger: 'blur' }],
    apiclient: [{ validator: validatePass, required: true, trigger: 'change' }]
});

const state = reactive({
    infoData: {
        ip: '',
        merchant_sn: '',
        pay_secret: '',
        wx_corp_id: '',
        merchant_certificate_serial: '',
        apiclient_cert: null,
        apiclient_key: null
    }
});

const onload = async () => {
    state.infoData = await getBusinesspay({});

    if (state.infoData.apiclient_cert && state.infoData.apiclient_key) {
        formRules.apiclient[0].required = false;
    }
};
const goBlank = (n: number) => {
    const url = {
        1: '/merchantconfig-guide',
        2: '/secretkeyconfig-guide',
        3: '/enterpriseconfig-guide',
        4: '/serial-number',
        5: '/certificateconfig-guide'
    };
    window.open(url[n]);
};

onMounted(() => {
    onload();
});

// 复制语句
const onCopy = async (val: any) => {
    try {
        await toClipboard(val);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

// 上传文件
const onHandleChange: UploadProps['onChange'] = (uploadFile: any, uploadFiles: any) => {
    fileList.value = uploadFiles;
    formInfo.value.validateField('apiclient', () => null);
};

// 删除文件
const onRemoveUpload = (uploadFile: any, uploadFiles: any) => {
    fileList.value = uploadFiles;
    formInfo.value.validateField('apiclient', () => null);
};

// 保存
const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid: boolean) => {
        if (valid) {
            if (fileList.value.length == 2) {
                const param1 = {
                    apiclient_cert: fileList.value[0].raw,
                    apiclient_key: fileList.value[1].raw
                };
                setSavePem(param1);
            }
            const param2 = {
                merchant_sn: state.infoData.merchant_sn,
                pay_secret: state.infoData.pay_secret,
                wx_corp_id: state.infoData.wx_corp_id,
                merchant_certificate_serial: state.infoData.merchant_certificate_serial
            };

            setBusinesspay(param2);
            ElMessage.success('保存成功');
        } else {
            ElMessage.error('请填写必填项');
        }
    });
};
</script>

<style lang="scss" scoped>
.title-box {
    height: 56px;
    display: flex;
    align-items: center;
    padding: 0 24px;
    border-bottom: 1px solid #d9d9d9;

    .title {
        font-size: 16px;
        font-weight: 500;
        color: #33302d;
    }
}

.el-form {
    padding: 24px;

    .ip-box {
        .el-button {
            margin-left: 30px;
        }
    }

    .cont-box {
        display: flex;
        align-items: center;

        .el-input,
        .upload-box {
            flex: 0 0 500px;
        }

        .tip-text {
            color: #969696;
        }

        .el-upload__tip {
            height: auto;
            line-height: 20px;
            margin-top: 0;
            color: #ff6b00;
        }
    }

    :deep .el-upload-dragger {
        width: 500px;
    }
}

.guide-text {
    margin-left: 30px;
    font-size: 14px;
    color: #ff6b00;
    text-decoration: none;
    cursor: pointer;
}

:deep .el-upload-list {
    .el-upload-list__item {
        width: 500px;
    }
}
</style>
